<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
        <!--工具栏-->
        <div class="head-container">
          <div v-if="crud.props.searchToggle">
            <!-- 搜索 -->
            <el-input
              v-model="query.waterTemperature"
              clearable
              size="small"
              placeholder="输入水温"
              style="width: 200px;"
              class="filter-item"
              @keyup.enter.native="crud.toQuery"
            />
            <rrOperation />
          </div>
          <crudOperation show="" :permission="permission" />
        </div>
        <!--表单渲染-->
        <el-dialog append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="700px">
          <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="96px">
            <el-form-item label="清澈度" prop="clarity">
              <el-input v-model="form.clarity" />
            </el-form-item>
            <el-form-item label="透明度" prop="transparency">
              <el-input v-model="form.transparency" />
            </el-form-item>

            <el-form-item label="气味" prop="smell">
              <el-input v-model="form.smell" />
            </el-form-item>
            <el-form-item label="水色" prop="waterColor">
              <el-input v-model="form.waterColor" />
            </el-form-item>
            <el-form-item label="PH值" prop="phValue">
              <el-input v-model="form.phValue" />
            </el-form-item>
            <el-form-item label="溶氧量" prop="oxygenContent">
              <el-input v-model="form.oxygenContent" />
            </el-form-item>
            <el-form-item label="水温" prop="waterTemperature">
              <el-input v-model="form.waterTemperature" />
            </el-form-item>
            <el-form-item label="水位" prop="waterLevel">
              <el-input v-model="form.waterLevel" />
            </el-form-item>
            <el-form-item label="流动性" prop="mobility">
              <el-input v-model="form.mobility" />
            </el-form-item>
            <el-form-item label="硬度" prop="hardness">
              <el-input v-model="form.hardness" />
            </el-form-item>
            <el-form-item label="生物指标（如藻类，微生物）" prop="biologicalContent">
              <el-input v-model="form.biologicalContent" />
            </el-form-item>

            <el-form-item label="是否开启灯光照射" prop="lighting">
              <el-switch
                v-model="form.lighting"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="是"
                inactive-text="否"
              />
            </el-form-item>
            <el-form-item label="图片" prop="url">
              <el-upload
                class="upload-demo"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                action=""
                :before-remove="beforeRemove"
                multiple
                :limit="1"
                :on-exceed="handleExceed"
                :file-list="form.fileList"
                :http-request="httpRequest"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
              </el-upload>
              <div v-if="form.fileId">
                <div style="height: 40px;width: 40px">
                  <img
                    :key="baseApi+`/api/file/download/`+form.fileId"
                    v-viewer
                    class="preview-image"
                    :src="baseApi+`/api/file/download/`+form.fileId"
                  >
                </div>
              </div>
            </el-form-item>
            <el-form-item label="说明" prop="description" style="display: inline-block">
              <el-input v-model="form.description" type="textarea" style="width: 250%" :rows="6" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="crud.cancelCU">取消</el-button>
            <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
          </div>
        </el-dialog>
        <!--表格渲染-->
        <el-table ref="table" v-loading="crud.loading" :data="crud.data" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
          <el-table-column :selectable="checkboxT" type="selection" width="55" />
          <el-table-column type="index" label="序号" width="50" />
          <el-table-column :show-overflow-tooltip="true" prop="clarity" label="清澈度" />
          <el-table-column :show-overflow-tooltip="true" prop="transparency" label="透明度" />
          <el-table-column :show-overflow-tooltip="true" prop="smell" label="气味" />
          <el-table-column :show-overflow-tooltip="true" prop="waterColor" label="水色" />
          <el-table-column :show-overflow-tooltip="true" prop="phValue" label="PH值" />
          <el-table-column :show-overflow-tooltip="true" prop="oxygenContent" label="溶氧量" />
          <el-table-column :show-overflow-tooltip="true" prop="waterTemperature" label="水温" />
          <el-table-column :show-overflow-tooltip="true" prop="mobility" label="流动性" />
          <el-table-column :show-overflow-tooltip="true" prop="hardness" label="硬度" />
          <el-table-column :show-overflow-tooltip="true" prop="waterLevel" label="水位" />
          <el-table-column :show-overflow-tooltip="true" prop="biologicalContent" label="生物指标（如藻类，微生物）" />
          <el-table-column :show-overflow-tooltip="true" prop="lighting" label="是否开启灯光照射" :formatter="formatLighting" />
          <el-table-column :show-overflow-tooltip="true" prop="description" label="说明" />
          <el-table-column :show-overflow-tooltip="true" prop="url" label="实物图片">
            <template slot-scope="scope">
              <div style="height: 40px;width: 40px">
                <img
                  :key="baseApi+`/api/file/download/`+scope.row.fileId"
                  v-viewer
                  class="preview-image"
                  :src="baseApi+`/api/file/download/`+scope.row.fileId"
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="createdUser" label="创建人" />
          <el-table-column :show-overflow-tooltip="true" prop="createdTime" label="创建时间" />
          <el-table-column
            v-permission="['admin','water:edit','water:del']"
            label="操作"
            width="115"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <udOperation
                :data="scope.row"
                :permission="permission"
              />
            </template>
          </el-table-column>
        </el-table>
        <pagination />
      </el-col>
    </el-row>
  </div>
</template>
<style scoped lang="scss">

</style>
<script>

import CRUD, { crud, form, header, presenter } from '@crud/crud'
import crudOperation from '@crud/CRUD.operation.vue'
import pagination from '@crud/Pagination'
import water from '@/api/pisciculture/water'
import rrOperation from '@crud/RR.operation.vue'
import udOperation from '@crud/UD.operation.vue'
import { validNumber } from '@/utils/validate'
import { initData, upload } from '@/api/data'
import item from '@/layout/components/Sidebar/Item.vue'
import { mapGetters } from 'vuex'
const defaultForm = { id: null, fileList: [], fileId: [], clarity: null, hardness: null, transparency: null, smell: null, waterColor: null, phValue: null, oxygenContent: null, waterTemperature: null, waterLevel: null, mobility: null, biologicalContent: null, lighting: false, description: null, url: null, status: 'true' }
let userEquipTypes = []
export default {
  name: 'Water',
  components: { crudOperation, rrOperation, udOperation, pagination },
  cruds() {
    return CRUD({ title: '水质', url: 'api/water', crudMethod: { ...water }, query: { enabled: 'true' }})
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    // 自定义验证
    const validNum = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入数量'))
      } else if (!validNumber(value)) {
        callback(new Error('请输入正确正整数'))
      } else {
        callback()
      }
    }
    const validUrl = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请上传实物图片'))
      } else {
        callback()
      }
    }
    return {
      photo: [], // 传递给图片查看器的image数据
      permission: {
        add: ['admin', 'water:add'],
        edit: ['admin', 'water:edit'],
        del: ['admin', 'water:del']
      },
      // equipTypes: [],
      rules: {
        zhName: [
          { required: true, message: '请输入设备名', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入描述信息', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 3000 个字符', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' },
          {
            pattern: /^(([1-9]{1}\d{0,9})|(0{1}))(\.\d{1,2})?$/,
            message: '请输入合法的金额数字，最多两位小数',
            trigger: 'blur'
          }
        ],
        num: [
          { required: true, message: '请输入数量', trigger: 'blur', validator: validNum }
        ],
        url: [
          { required: true, message: '请上传实物图片', trigger: 'blur', validator: validUrl }
        ]
      }
    }
  },
  computed: {
    item() {
      return item
    },

    ...mapGetters([
      'baseApi'
    ])
  },
  mounted() {
    this.$nextTick(() => {
      const showViews = this.$refs.showView
      console.log(showViews) // 这里将会是一个包含所有.showView元素的数组
    })
  },
  methods: {
    formatLighting(row, column, cellValue) {
      var ret = '' // 你想在页面展示的值
      if (cellValue) {
        ret = '是' // 根据自己的需求设定
      } else {
        ret = '否'
      }
      return ret
    },
    // 实现图片上传功能
    httpRequest(items) {
      // var imgId = items.file.lastModified
      console.log(items.file.name)
      this.form.fileList.push({ name: items.file.name })
      var formData = new FormData()
      formData.append('file', items.file)
      upload(formData)
        .then(res => {
          this.form.fileId = res.data.id
          this.form.url = res.data.fileName
          // this.fileList[0].name = items.file.name
          console.log('this.form.url', this.form.fileName)
        })
        .catch(() => { })
    },
    handleRemove(file, fileList) {
      this.form.fileList = []
      this.form.url = null
      this.form.fileId = null
      console.log('删除', fileList)
    },
    handlePreview(file) {
      console.log(file)
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`)
    },
    changeEquipTypes() {
      console.log('value', form.equipType)
    },
    [CRUD.HOOK.afterAddError](crud) {
      this.afterErrorMethod(crud)
    },
    [CRUD.HOOK.afterEditError](crud) {
      this.afterErrorMethod(crud)
    },
    afterErrorMethod(crud) {
      // 恢复select
      const initEquipTypes = []
      userEquipTypes.forEach(function(equipType, index) {
        initEquipTypes.push(equipType.id)
      })
      // crud.form.equipTypes = initEquipTypes
    },
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      // this.getEquipTypes(2)
    },
    // 打开编辑弹窗前做的操作
    [CRUD.HOOK.beforeToEdit](crud, form) {
      // this.getEquipTypes(2)
      userEquipTypes = []
      // const equipTypes = []
      /* form.equipTypes.forEach(function(equipType, index) {
        equipTypes.push(equipType.id)
        // 初始化编辑时候的岗位
        // const data = { id: job.id }
        userEquipTypes.push(equipType.id)
      })
      form.equipTypes = equipTypes*/
    },
    // 提交前做的操作
    [CRUD.HOOK.afterValidateCU](crud) {
      if (crud.form.description == null) {
        this.$message({
          message: '说明不能为空',
          type: 'warning'
        })
        return false
      }
      return true
    },
    // 提交之后
    [CRUD.HOOK.afterSubmit](crud) {
      crud.form.url = null
      this.fileList = []
    },
    checkboxT(row, rowIndex) {
      return row.id !== 1
    },
    getEquipTypes(dictTypeId) {
      var _this = this
      initData('/api/dict_value', { typeId: dictTypeId }).then(res => {
        console.log(res)
        var dicts = res.data.records
        _this.equipTypes = []
        dicts.forEach(function(dict, index) {
          _this.equipTypes.push({ id: dict.dict_code, name: dict.dict_name })
        })
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .vue-treeselect__control,::v-deep .vue-treeselect__placeholder,::v-deep .vue-treeselect__single-value {
  height: 30px;
  line-height: 30px;
}
.upload-demo {
  width: 460px;
}
.fullscreen-preview {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.preview-image {
  max-width: 100%;
  max-height: 100%;
  position: relative;
  cursor: zoom-in;
}
</style>
